package com.bw.module_cinema

import android.util.Log
import android.view.View
import android.content.Intent
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bw.lib_common.base.BaseMVIFragment
import com.bw.lib_storage.db.DBUtils
import com.bw.module_cinema.databinding.FragmentCinemaBinding
import com.bw.module_cinema.intent.CinemaIntent
import com.bw.module_cinema.model.adapter.NewTypeAdapter
import com.bw.module_cinema.model.adapter.TypeAdapter
import com.bw.module_cinema.model.adapter.VideoByTypeIdAdapter
import com.bw.module_cinema.model.entity.VideoByTypeIdEntity
import com.bw.module_cinema.model.state.CinemaState
import com.bw.module_cinema.model.viewmodel.CinemaViewModel
import com.bw.module_cinema.search.SearchActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.math.log

@AndroidEntryPoint
class CinemaFragment : BaseMVIFragment() {
    companion object{
        private const val TAG = "CinemaFragment"
    }
    private val binding :FragmentCinemaBinding by lazy {
        FragmentCinemaBinding.inflate(layoutInflater)
    }
    private var typeid : Int = 20
    private var pid : Int = 1
//    private var typeDialog: TypeDialog? = null // 弹窗实例
    private lateinit var mAdapter : TypeAdapter
    private lateinit var mNewAdapter: NewTypeAdapter
    private lateinit var mVideoAdapter: VideoByTypeIdAdapter

    private lateinit var mViewModel : CinemaViewModel

    private val starDao by lazy {
        DBUtils.getDB().videoStarDao()
    }

    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[CinemaViewModel::class.java]
    }

    override fun getFragmentRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()
        mAdapter = TypeAdapter()
        binding.rvType.layoutManager = LinearLayoutManager(
            context,LinearLayoutManager.HORIZONTAL,false
        )
        binding.rvType.adapter = mAdapter

        mNewAdapter = NewTypeAdapter()
        binding.rvSubType.layoutManager = GridLayoutManager(requireContext(), 4)
        binding.rvSubType.adapter = mNewAdapter
        binding.rvSubType.visibility = View.GONE

        mVideoAdapter = VideoByTypeIdAdapter()
        binding.rvVideo.layoutManager = GridLayoutManager(requireContext(),2)
        binding.rvVideo.adapter = mVideoAdapter

        // open search activity when clicking the search bar
        binding.searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                startActivity(Intent(requireContext(), com.bw.module_cinema.search.SearchActivity::class.java))
                binding.searchView.clearFocus()
            }
        }

        binding.searchView.setOnSearchClickListener {
            startActivity(Intent(requireContext(), com.bw.module_cinema.search.SearchActivity::class.java))
            binding.searchView.clearFocus()
        }

//        typeDialog = TypeDialog(requireContext())
        mAdapter.setOnTypeItemClickListener(object : TypeAdapter.OnTypeItemClickListener{
            override fun onItemClick(id: Int) {
                binding.rvSubType.visibility = if (binding.rvSubType.visibility == View.VISIBLE){
                    View.GONE
                }else{
                    View.VISIBLE
                }
//                typeDialog?.show()

                // 通过ViewModel发送"根据pid获取数据"的意图
                lifecycleScope.launch {
                    mViewModel.intents.send(CinemaIntent.getMutilTypeByPid(id))
                }
            }
        })

        mNewAdapter.setOnItemClickListener(object : NewTypeAdapter.OnItemClickListener{
            override fun onItemClick(typeid: Int) {
                binding.rvSubType.visibility = View.GONE
                lifecycleScope.launch {
                    mViewModel.intents.send(CinemaIntent.getVideoByTypeId(1,10,typeid))
                }
            }

        })


        // 视频适配器设置收藏点击事件
        mVideoAdapter.setOnStarClickListener { videoEntity, isCollected ->
            lifecycleScope.launch {
                try {
                    if (isCollected) {
                        // 收藏 - 将VideoByTypeIdEntity转换为VideoStarEntity
                        val starEntity = com.bw.lib_storage.db.entity.VideoStarEntity(
                            id = videoEntity.id,
                            title = videoEntity.title,
                            toutiaolvideotext = videoEntity.toutiaolvideotext,
                            videomainimag = videoEntity.videomainimag
                        )
                        starDao.insert(starEntity)
                        showMsg("收藏成功")
                    } else {
                        // 取消收藏
                        mViewModel.cancelCollect(videoEntity)
                        showMsg("取消收藏")
                    }
                } catch (e: Exception) {
                    showMsg("操作失败: ${e.message}")
                }
            }
        }

        mVideoAdapter.setOnItemClickListener(object : VideoByTypeIdAdapter.OnVideoItemClickListener{
            override fun onItemClick(entity: VideoByTypeIdEntity) {
                startActivity(Intent(requireContext(), com.bw.module_detail.MainActivity::class.java).apply {
                    putExtra("videoPath", entity.videopath)
                    putExtra("albumId", entity.albumid)
                    putExtra("icon", entity.avatar_url)
                    putExtra("name", entity.title)
                    putExtra("description", entity.toutiaolvideotext)
                    putExtra("duration", entity.duration)
                    Log.d("TAG", "onItemClick: ${entity.avatar_url}")
                })
            }
        })
    }

    override fun initData() {
        super.initData()
        //结合 repeatOnLifecycle 执行周期性 / 持续性任务
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                mViewModel.intents.send(CinemaIntent.getMutilType)
                mViewModel.intents.send(CinemaIntent.getVideoByTypeId(1, 10, typeid))
            }
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                launch {
                    mViewModel.typeStateFlow_.collect{ oldState ->
                        when(oldState){
                            is CinemaState.Empty -> {
                                showMsg("空数据")
                            }
                            is CinemaState.Success -> {
                                mAdapter.setData(oldState.data)
                            }
                            is CinemaState.Error -> {
                                showMsg("失败"+oldState.message)
                            }
                            else ->{}
                        }
                    }
                }
                launch {
                    mViewModel.newTypeStateFlow_.collect{ newState ->
                        when(newState){
                            is CinemaState.Empty -> {
                                showMsg("空数据")
                            }
                            is CinemaState.Success -> {
                                Log.d(TAG, "子类型数据总数：${newState.data.size}")
                                mNewAdapter.updateData(newState.data)
                                // 强制刷新布局，重新计算高度
                                binding.rvSubType.post {
                                    binding.rvSubType.requestLayout()
                                }
                            }
                            is CinemaState.Error -> {
                                showMsg("失败"+newState.message)
                            }
                            else ->{}
                        }
                    }
                }
                launch {
                    mViewModel.videoStateFlow_.collect{ video ->
                        when(video){
                            is CinemaState.Empty -> {
                                showMsg("空数据")
                            }
                            is CinemaState.VideoSuccess -> {
                                // 从数据库加载收藏状态并更新到视频列表
                                loadFavoriteStatusForVideos(video.data)
                            }
                            is CinemaState.Error -> {
                                showMsg("失败"+video.message)
                            }
                            else ->{}
                        }
                    }
                }
            }
        }
    }

    /**
     * 从数据库加载收藏状态并更新到视频列表
     */
    private fun loadFavoriteStatusForVideos(videoList: List<com.bw.module_cinema.model.entity.VideoByTypeIdEntity>) {
        lifecycleScope.launch {
            kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
                try {
                    // 获取所有已收藏的视频ID
                    val favoriteIds = starDao.getAllFavorites().map { it.id }.toSet()
                    
                    // 更新每个视频的收藏状态
                    videoList.forEach { video ->
                        video.isStar = favoriteIds.contains(video.id)
                    }
                    
                    // 在主线程更新UI
                    kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                        mVideoAdapter.setData(videoList)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "加载收藏状态失败: ${e.message}")
                    // 如果加载失败，仍然显示视频列表（默认为未收藏）
                    kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
                        mVideoAdapter.setData(videoList)
                    }
                }
            }
        }
    }

    // 页面销毁时释放弹窗，避免内存泄漏
//    override fun onDestroyView() {
//        super.onDestroyView()
//        typeDialog?.dismiss()
//        typeDialog = null
//    }
}